package com.sjyy.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.UUID;
import com.aliyun.openservices.oss.OSSClient;
import com.aliyun.openservices.oss.model.ObjectMetadata;
import com.aliyun.openservices.oss.model.PutObjectResult;

public class OSSUtil {

	private static final String KEY = "3q6uXc44NswROpbV";
	private static final String SECRET = "bfAZxQYTYEC3Z6iLE8HkCknA0R1Fkm";
	private static final int EXPIRATION = 10;
	private static final String BUCKETNAME = "purchases-image";
	private static final int year = 2114;
	
	private OSSClient ossClient;
	private String bucketName ;
	
	public OSSUtil(){
		ossClient = new OSSClient(KEY,SECRET);
		this.setBucketName(BUCKETNAME);
		createBucket();
	}
	
	//创建Bucket 创建前set BucketName的值
	private void createBucket() {
		// 获取Bucket的存在信息
		boolean exists = ossClient.doesBucketExist(bucketName);

		// 输出结果
		if (!exists) {
			// 新建一个Bucket
			ossClient.createBucket(bucketName);
		}
	}
	
	//基本上传
	public String putObject(String filePath) throws FileNotFoundException {

		String key = getUUKEY();
	    // 获取指定文件的输入流
	    File file = new File(filePath);
	    InputStream content = new FileInputStream(file);

	    // 创建上传Object的Metadata
	    ObjectMetadata meta = new ObjectMetadata();

	    // 必须设置ContentLength
	    meta.setContentLength(file.length());

	    // 上传Object.
	    PutObjectResult result = ossClient.putObject(bucketName, key, content, meta);

	    // 打印ETag
	    System.out.println(result.getETag());
	    
	    return key;
	}
	
	//通过Object的key 获取URL
	public URL getUrl(String key){
		// 设置URL过期时间为1小时
		Date expiration = new Date(new Date(year,1,1).getTime() + EXPIRATION*60 * 1000);

		// 生成URL
		URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
		
		return url;
	}
	
	//生成唯一的值
	private String getUUKEY(){
		return UUID.randomUUID().toString();
	}	
	
	public String getBucketName() {
		return bucketName;
	}
	
	public void setBucketName(String bucketName) {
		this.bucketName = bucketName;
	}
}
